package com.ilop.sthome.ui.activity.config;

import android.content.Intent;
import android.text.method.LinkMovementMethod;
import android.view.View;

import com.aliyun.alink.business.devicecenter.api.add.AddDeviceBiz;
import com.example.common.utils.MediaPlayerUtil;
import com.example.common.utils.SpUtil;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.mvp.contract.config.ConnectNetContract;
import com.ilop.sthome.mvp.present.config.ConnectNetPresenter;
import com.ilop.sthome.ui.activity.device.GatewayMainActivity;
import com.ilop.sthome.ui.activity.main.ContainLoginActivity;
import com.ilop.sthome.ui.activity.main.MainActivity;
import com.siterwell.familywellplus.R;
import com.siterwell.familywellplus.databinding.ActivityConnectNetBinding;

/**
 * @author skygge
 * @date 2019-10-28.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：配网页面
 */
public class ConnectNetActivity extends ContainLoginActivity<ConnectNetPresenter, ActivityConnectNetBinding> implements ConnectNetContract.IView {

    private String mWiFiSSId;
    private String mWiFiPwd;
    private boolean mWiFiType;
    private boolean mAlreadyInRoom = false;
    private MediaPlayerUtil mMediaPlayer;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_connect_net;
    }

    @Override
    protected void initialize() {
        super.initialize();
        mWiFiSSId = getIntent().getStringExtra(CommonId.KEY_WIFI_SSID);
        mWiFiPwd = getIntent().getStringExtra(CommonId.KEY_WIFI_PWD);
        mWiFiType = getIntent().getBooleanExtra(CommonId.KEY_WIFI_AP,false);
    }

    @Override
    protected void initPresent() {
        super.initPresent();
        mPresent = new ConnectNetPresenter(mContext, mHandler);
    }

    @Override
    protected void initView() {
        super.initView();
        mPresent.getInitialization(mWiFiSSId, mWiFiPwd, mWiFiType);
        String mTipMsg = mWiFiType ? getString(R.string.waiting_for_device_connection):getString(R.string.esptouch_is_configuring);
        mDBind.tvTip.setText(mTipMsg);
        mDBind.connectStatus.loadLoading();
    }

    @Override
    protected void initData() {
        super.initData();
        mPresent.smartOrApConnect(mWiFiType);//进行配网
    }

    @Override
    protected void initListener() {
        super.initListener();
        mDBind.retry.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            if (mAlreadyInRoom){
                intent.setClass(mContext, MainActivity.class);
            }else {
                intent.setClass(mContext, AddGatewayGuideActivity.class);
            }
            startActivity(intent);
        });

        mDBind.ivConnectBack.setOnClickListener(v -> {
            mPresent.removeProductInfo();
            finish();
        });

        mDBind.changeConfig.setOnClickListener(view -> {
            Intent intent = new Intent(mContext, SetPhoneApActivity.class);
            intent.putExtra(CommonId.KEY_WIFI_SSID, mWiFiSSId);
            intent.putExtra(CommonId.KEY_WIFI_PWD, mWiFiPwd);
            startActivity(intent);
            finish();
        });
    }

    @Override
    public void showInitializationView() {
        mDBind.failReason.setText(mPresent.getReasonSpan());
        mDBind.failReason.setMovementMethod(LinkMovementMethod.getInstance());
        mDBind.failReason.setVisibility(View.INVISIBLE);
        mDBind.restoreFactory.setText(mPresent.getRestoreFactory());
        mDBind.restoreFactory.setMovementMethod(LinkMovementMethod.getInstance());
        mDBind.restoreFactory.setVisibility(View.INVISIBLE);
        mDBind.changeConfig.setVisibility(View.INVISIBLE);
        mDBind.retry.setVisibility(View.INVISIBLE);
        mDBind.changeConfig.setVisibility(View.INVISIBLE);
    }

    @Override
    public void showCurrentProgress(String progress) {
        mDBind.tvProgressNum.setText(progress);
    }

    @Override
    public void showConnectNetSuccess(String deviceName) {
        String tips = String.format(mContext.getString(R.string.is_connected_to_wifi), deviceName);
        mDBind.tvTip.setText(tips);
        SpUtil.putString(mContext, mWiFiSSId, mWiFiPwd);
    }

    @Override
    public void showConnectNetError(int status, String msg) {
        mDBind.tvProgressNum.setVisibility(View.GONE);
        mDBind.connectStatus.loadFailure();
        mDBind.failReason.setVisibility(View.VISIBLE);
        mDBind.changeConfig.setVisibility(View.VISIBLE);
        mDBind.retry.setVisibility(View.VISIBLE);
        mDBind.retry.setText(getString(R.string.retry));
        switch (status){
            case -1://代表配网超时失败
                mDBind.tvTip.setText(getString(R.string.config_net_fail));
                break;
            case 0: //代表参数错误
            case 2: //代表配网失败 接口返回
                mDBind.tvTip.setText(msg);
                break;
            case 3: //代表已被绑定
                mDBind.restoreFactory.setVisibility(View.VISIBLE);
                mDBind.tvTip.setText(getString(R.string.initialzation_guidance_mention1));
                break;
            case 4: //代表回调绑定失败
                mDBind.restoreFactory.setVisibility(View.VISIBLE);
                mDBind.tvTip.setText(msg);
                break;
        }
    }

    @Override
    public void showConnectMessage(String msg) {
        mDBind.tvTip.setText(msg);
    }

    @Override
    public void bindSuccess(String deviceName) {
        mDBind.tvProgressNum.setVisibility(View.GONE);
        mMediaPlayer = new MediaPlayerUtil(mContext);
        mMediaPlayer.playSuccess();
        mDBind.connectStatus.loadSuccess();
        mDBind.tvTip.setText(getString(R.string.success));
        Intent intent = new Intent(mContext, GatewayMainActivity.class);
        intent.putExtra(CommonId.KEY_ADD_NEW, true);
        intent.putExtra(CommonId.KEY_DEVICE_NAME, deviceName);
        mHandler.postDelayed(()->{
            startActivity(intent);
            finish();
        },1500);
    }

    @Override
    public void showAlreadyInRoom(String deviceName) {
        showToast(R.string.the_gateway_already_exists_in_the_room);
        this.mAlreadyInRoom = true;
        mDBind.connectStatus.loadSuccess();
        mDBind.tvProgressNum.setVisibility(View.GONE);
        mDBind.changeConfig.setVisibility(View.GONE);
        mDBind.retry.setVisibility(View.GONE);
        mPresent.skipToGateway(deviceName);
    }

    @Override
    public void showToastMsg(String msg) {
        showToast(msg);
    }

    @Override
    public void startActivityByIntent(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void startForResultByIntent(Intent intent) {
        startActivityForResult(intent, 1);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mPresent.removeProductInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresent.removeProductInfo();
        AddDeviceBiz.getInstance().stopAddDevice();
        if (mMediaPlayer!=null) {
            mMediaPlayer.destroy();
        }
    }
}
